using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using tafei_thingsapi.Models;

namespace tafei_thingsapi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DeviceSharesController : ControllerBase
    {
        private readonly tafei_thingsapiContext _context;

        public DeviceSharesController(tafei_thingsapiContext context)
        {
            _context = context;
        }

        // 获取设备的所有分享记录
        [HttpGet("device/{deviceId}")]
        public async Task<ActionResult<IEnumerable<DeviceShare>>> GetDeviceShares(int deviceId)
        {
            return await _context.DeviceShares
                .Include(ds => ds.SharedUser)
                .Where(ds => ds.DeviceId == deviceId && ds.IsActive)
                .ToListAsync();
        }

        // 获取用户被分享的设备
        [HttpGet("user/{userId}")]
        public async Task<ActionResult<IEnumerable<DeviceShare>>> GetUserSharedDevices(int userId)
        {
            return await _context.DeviceShares
                .Include(ds => ds.Device)
                .Where(ds => ds.SharedUserId == userId && ds.IsActive)
                .ToListAsync();
        }

        // 分享设备给用户
        [HttpPost]
        public async Task<ActionResult<DeviceShare>> ShareDevice(DeviceShare deviceShare)
        {
            // 检查设备是否存在
            var device = await _context.Devices.FindAsync(deviceShare.DeviceId);
            if (device == null)
            {
                return NotFound(new { message = "设备不存在" });
            }

            // 检查用户是否存在
            var user = await _context.Users.FindAsync(deviceShare.SharedUserId);
            if (user == null)
            {
                return NotFound(new { message = "用户不存在" });
            }

            // 检查是否已经分享过
            var existingShare = await _context.DeviceShares
                .FirstOrDefaultAsync(ds => ds.DeviceId == deviceShare.DeviceId && 
                                         ds.SharedUserId == deviceShare.SharedUserId);
            
            if (existingShare != null)
            {
                if (existingShare.IsActive)
                {
                    return BadRequest(new { message = "设备已经分享给该用户" });
                }
                else
                {
                    // 如果之前分享过但已取消，重新激活
                    existingShare.IsActive = true;
                    existingShare.SharedAt = System.DateTime.Now;
                    await _context.SaveChangesAsync();
                    return Ok(existingShare);
                }
            }

            _context.DeviceShares.Add(deviceShare);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetDeviceShares), new { deviceId = deviceShare.DeviceId }, deviceShare);
        }

        // 取消设备分享
        [HttpDelete("{id}")]
        public async Task<IActionResult> CancelShare(int id)
        {
            var deviceShare = await _context.DeviceShares.FindAsync(id);
            if (deviceShare == null)
            {
                return NotFound(new { message = "分享记录不存在" });
            }

            deviceShare.IsActive = false;
            await _context.SaveChangesAsync();

            return Ok(new { message = "分享已取消" });
        }
    }
} 